// import {globalData} from '../../utils/global-data';
import {getCurrentAudioLesson} from '../../common/service/courses-service';
import {getMyCourse} from '../../data-model/model-user';
import {getUserInfo, getLoginStatus} from '../../common/service/user-service';
import {getWxUserInfo, makePhoneCall} from '../../common/service/system-service';
import {navigateTo, stopPullDownRefresh} from '../../common/service/page-service';
import {eventBusGetter} from '../../utils/eventbus';
import {routerGetter} from '../../utils/router';
import {LOGIN_STATUS, EVENT_BUS_KEY, CUSTOMER_SERVICE_PHONE} from '../../common/constants';
import {formIdCollect} from '../../data-model/model-form';

Page({
    data: {
        firstOnShow: true,
        courses: undefined,
        refreshStatus: 0,
        isLogin: false,
        name: '',
        avatar: '',
        company: '',
        position: '',
        isComplete: false, // 我的信息是否已完善
        isPullToRefresh: false
    },
    onLoad () {
        console.log('我的页面初始化onLoad');
        this.refreshPage.bind(this);
        // 登录状态改变 刷新个人信息和列表
        eventBusGetter().$on(EVENT_BUS_KEY.LOGIN_STATUS_UPDATE, this.refreshPage);
        // 完善我的信息 刷新个人信息和列表
        eventBusGetter().$on(EVENT_BUS_KEY.REFRESH_MY_COURSE, this.refreshPage);
        // 购买成功通知 刷新已购列表
        eventBusGetter().$on(EVENT_BUS_KEY.PAY_COURSE_SUCCESS, this.getCourses);
        let that = this;
        // 判断userInfo是否有头像姓名 如果没有获取微信头像姓名
        // 1. 未登录, 2 已登录但没有头像 姓名
        if (!this.data.isLogin || (!this.data.name && !this.data.avatar)) {
            getWxUserInfo()
                .then(res => {
                    if (!that.data.isLogin || (!that.data.name && !that.data.avatar)) {
                        that.setData({
                            name: res.userInfo.nickName,
                            avatar: res.userInfo.avatarUrl
                        });
                    }
                })
                .catch(err => {
                    if (err.errMsg === ('getUserInfo:fail auth deny' || 'getUserInfo:fail:auth deny')) {
                        console.log('用户拒绝授权');
                    }
                });
        }
        this.refreshUserInfo();
    },
    onShow () {
        // 除第一次显示外每次显示都需要重新刷新已购课程列表（防止重复请求）
        if (!this.data.firstOnShow) {
            this.getCourses();
        } else {
            this.data.firstOnShow = false;
        }
        // 播放器状态同步
        this.setData({
            refreshStatus: new Date().getTime()
        });
    },
    onUnload () {
        eventBusGetter().$off(EVENT_BUS_KEY.LOGIN_STATUS_UPDATE, this.refreshPage);
        eventBusGetter().$off(EVENT_BUS_KEY.REFRESH_MY_COURSE, this.refreshPage);
    },
    onRightTextClick () {
        navigateTo({url: '/pages/baseinfo/baseinfo'});
    },
    onLoginClick () {
        navigateTo({url: '/pages/login/login'});
    },
    onClickPhone () {
        makePhoneCall({
            phoneNumber: CUSTOMER_SERVICE_PHONE
        }).then(res => {
            console.log('拨打电话成功', res);
        }).catch(err => {
            console.log('设备不支持打电话', err);
        });
    },
    onCourseClick (event) {
        let uri = event.currentTarget.dataset.uri;
        console.log(uri);
        if (uri) {
            routerGetter().execute(uri);
        }
    },
    onPullDownRefresh () {
        this.data.isPullToRefresh = true;
        this.getCourses();
    },
    refreshUserInfo () {
        let user = getUserInfo();
        console.log('我的页面user刷新, user数据', user);
        if (user) {
            let isComplete = (user.industry && user.userPosition && user.userCompany && user.userAvatar && user.name);
            this.setData({
                isLogin: true,
                name: user.name ? user.name : '',
                avatar: user.userAvatar ? user.userAvatar : '',
                company: user.userCompany ? user.userCompany : '',
                position: user.userPosition ? user.userPosition : '',
                isComplete: !!isComplete
            });
            this.getCourses();
        } else {
            this.setData({
                isLogin: false
            });
        }
    },
    getCourses () {
        let that = this;
        getMyCourse()
            .then(courses => {
                if (that.data.isPullToRefresh) {
                    stopPullDownRefresh();
                    that.data.isPullToRefresh = false;
                }
                that.setData({
                    courses: courses
                });
            })
            .catch(err => {
                if (that.data.isPullToRefresh) {
                    stopPullDownRefresh();
                    that.data.isPullToRefresh = false;
                }
                console.log('获取我的已购课程列表失败', err);
            });
    },
    refreshPage (status) {
        if (status) {
            console.log('我的页面接收到EventBus刷新通知, 执行userInfo刷新显示');
        }
        let that = this;
        if (getLoginStatus() === LOGIN_STATUS.ZH_LOGIN_SUCCESS || getLoginStatus() === LOGIN_STATUS.ZH_LOGIN_FAILED) {
            that.refreshUserInfo();
        }
    },
    fromSubmit (e) {
        formIdCollect(e.detail.formId);
    }
});
